<template>
<div>
       <!--导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>资讯管理</el-breadcrumb-item>
        <el-breadcrumb-item>广告列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
          <el-row :gutter="25">
              <el-col :span="5">
                  <el-input size="small" clearable placeholder="输入标题" v-model="queryParams.title" /> 
              </el-col>
              <el-col :span="5">
                  <el-select v-model="queryParams.status" filterable clearable placeholder="状态" size="small">
                    <el-option
                    v-for="item in statusList"
                    :key="item.id"
                    :label="item.keyDesc"
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-col>
              <el-col :span="1" style="margin-left:28px">
                  <el-button size="small" type="success" @click="queryPage" icon="el-icon-search" v-if="permissionStrValue.indexOf('message:query') !== -1">查询</el-button>
              </el-col>
              <el-col :span="1" style="margin-left:28px">
                  <el-button size="small" type="primary" @click="add" icon="el-icon-plus" v-if="permissionStrValue.indexOf('message:add') !== -1">新增</el-button>
              </el-col>
          </el-row>

          <!--放表格-->
        <el-table :data="list" border >
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="广告标题">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="广告封面">
                <template slot-scope="scope">
                    <el-image
                        style="width: 100px; height: 100px"
                        :src="scope.row.image"
                ></el-image>
                </template>
            </el-table-column>
            <el-table-column label="广告链接">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.url }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <span style="color:red" size="medium">{{ scope.row.status }}</span>
                </template>
            </el-table-column>
            <el-table-column label="排序值">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.sort }}</span>
                </template>
            </el-table-column>
            <el-table-column label="开始时间">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.startTime}}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.endTime}}</span>
                </template>
            </el-table-column>
            <el-table-column label="发布时间">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.createTime}}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="250px">
                 <template slot-scope="scope">
                     <el-button type="warning" size="small" @click="updateById(scope.row.id)" icon="el-icon-edit" v-if="permissionStrValue.indexOf('message:update') !== -1 && scope.row.status !== '无效'">更改为失效</el-button>
                     <el-button type="danger" size="small" @click="removeById(scope.row.id)" icon="el-icon-delete" v-if="permissionStrValue.indexOf('message:delete') !== -1">删除</el-button>
                 </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.currPage"
          :page-sizes="[10,20, 30, 40, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <el-dialog
       title="新增数据"
       :visible.sync="addFlag"
       width="40%"
       @close="clearForm()">
       <el-form :model="messageObj" label-width="100px" ref="messageObj" label-position="left" :rules="messageObjRules">
         <el-form-item label="标题:" prop="title">
           <el-input v-model="messageObj.title" size="small" ></el-input>
         </el-form-item>
         <el-form-item label="链接:" >
           <el-input v-model="messageObj.url" size="small" ></el-input>
         </el-form-item>
         <el-form-item label="排序字段:" prop="sort">
           <el-input v-model="messageObj.sort" size="small" ></el-input>
         </el-form-item>
         <el-form-item label="有效时间段:" prop="dataValue">
           <el-date-picker
                    v-model="messageObj.dataValue"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="small"
                    @change="initTime"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
         </el-form-item>
         <el-form-item label="图片:" >
           <el-upload
                action="http://121.199.58.229:8180/oss/file/test"
                list-type="picture-card"
                :on-change="beforeProductUpload"
                :auto-upload="false"
                >
                <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="imageDialog">
            <img width="100%" :src="messageObj.dialogImageUrl" alt />
            </el-dialog>
         </el-form-item>
       </el-form>
       <span slot="footer" class="dialog-footer">
          <el-button @click="addFlag = false">取 消</el-button>
          <el-button type="primary" @click="addData()">确 定</el-button>
       </span>
     </el-dialog>

      </el-card>

</div>
    
</template>
<script>
export default {
    name: 'Message',
    data() {
        return {
             queryParams: {
                title: '',
                status: '',
                currPage: 1,
                pageSize: 10
            },
            messageObj: {
                title: '',
                sort: '',
                url: '',
                dataValue: '',
                startTime: '',
                endTime: '',
                dialogImageUrl: '',
                fileList: [],

            },
            list: [],
            total: 0,
            statusList: [],
            messageObjRules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
               ],
               dataValue: [
                   { required: true, message: '请输入有效时间', trigger: 'blur' }
               ],
               sort: [
                   { required: true, message: '请输入排序值', trigger: 'blur' }
               ]

            },
            imageDialog: false,
            addFlag: false,
            permissionStrValue: ''

        }
    },
    created() {
        this.queryPage();
        //获取权限值
       this.permissionStrValue = JSON.parse(window.sessionStorage.getItem('permissionList')).toString();
    },
    methods: {
        async queryPage() {
            const{data: res} = await this.$http.post('/house/advertise/list-page', JSON.stringify(this.queryParams), {
                 headers: {
                            'Content-Type': 'application/json;charset=UTF-8',
                }
            })
            if(!res.success) {
                return this.$message.error(res.message);
            }
            console.log(res)
            this.list = res.data;
            this.total = res.total;

        },
        add() {
            this.addFlag = true;
            //this.addData();

        },
        async updateById(id) {
            const confirmResult = await this.$confirm('是否将改资讯更改为失效?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => {
                return err;
            });
            //当用户确认时，则返回值为字符串：confirm
            //取消时，返回字符串cancel
            if (confirmResult !== 'confirm'){
                return this.$message.info("已取消更改")
            }
            const{data: res} = await this.$http.put('/house/advertise/update-status/' + id + '/' + '2');
            if(res.success) {
                this.$message.success("更改成功！");
                this.queryPage();
            } else {
                this.$message.error(res.message);
            }
        },
        async removeById(id) {
             const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => {
                return err;
            });
            //当用户确认时，则返回值为字符串：confirm
            //取消时，返回字符串cancel
            if (confirmResult !== 'confirm'){
                return this.$message.info("已取消删除")
            }
            //
            const{data: res} = await this.$http.delete('/house/advertise/delete/' + id);
            if(res.success) {
                this.$message.success("删除成功！");
                this.queryPage();
            } else {
                this.$message.error(res.message);
            }


        },
        async getStatusList() {
            var params = new Object();
            params.pageSize = 100;
            params.currPage = 1;
            params.type = '资讯状态';
            const{data: res} = await this.$http.post('/base-data/list-page', JSON.stringify(params), {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                }
            })
            if(!res.success) {
                return this.$message.error(res.message);
            }
            console.log(res)
            this.statusList = res.data

        },
        clearForm() {
            this.messageObj.title = '';
            this.messageObj.sort = '';
            this.messageObj.url = '';
            this.messageObj.dataValue = '';
            this.messageObj.startTime = '';
            this.messageObj.endTime = '';
            this.messageObj.fileList = [];
            this.messageObj.dialogImageUrl = '';

        },
        initTime(val) {
            if(val !== null) {
               this.messageObj.startTime = this.dateFormat(val[0]);
               this.messageObj.endTime = this.dateFormat(val[1]);
            // this.messageObj.startTime = val[0];
            // this.messageObj.endTime = val[1];
            }
        },
        beforeProductUpload(file) {
            this.messageObj.fileList.push(file);
        },
        handleSizeChange(newPageSize) {
            this.queryParams.pageSize = newPageSize;
            this.queryPage();
        },
        handleCurrentChange(newPage) {
            this.queryParams.currPage = newPage;
            this.queryPage();

        },
        dateFormat(dateData) {
            var date = new Date(dateData)
            var y = date.getFullYear()
            var m = date.getMonth() + 1
            m = m < 10 ? ('0' + m) : m
            var d = date.getDate()
            d = d < 10 ? ('0' + d) : d
            const time = y + '-' + m + '-' + d + " 00:00:00"
            return time;
        },
        addData() {
            this.$refs.messageObj.validate(async valid => {
                if(valid) {
                    var fd = new FormData();
                    fd.append("title", this.messageObj.title);
                    fd.append("sort", this.messageObj.sort);
                    fd.append("startTime", this.messageObj.startTime);
                    fd.append("endTime", this.messageObj.endTime);
                    fd.append("url", this.messageObj.url);
                    if(this.messageObj.fileList.length > 0) {
                        fd.append("image", this.messageObj.fileList[0].raw);
                    }
                    const {data: res} = await this.$http.post('/house/advertise/add', fd)
                    
                    if(res.success) {
                        this.$message.success("增加成功！");
                        this.addFlag = false;
                        this.clearForm();
                        this.queryPage();
                        this.messageObj.fileList = [];
                    } else{
                        this.$message.error(res.message);
                    }
                }
            })

        }
    }
}
</script>
<style scoped>

</style>